<template>
  <div class="container">
    <div class="search-container">
      <el-input v-model="searchId" placeholder="请输入床位 ID 进行查询"></el-input>
      <el-button type="primary" @click="queryBedById">查询</el-button>
    </div>
    <el-button type="primary" @click="openCreateDialog">新增床位</el-button>
    <el-table :data="beds" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="buildingNo" label="楼号" />
      <el-table-column prop="bedNo" label="床位号" />
      <el-table-column prop="roomNo" label="房间号" />
      <el-table-column prop="bedStatus" label="状态" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button v-if="row.bedStatus === 'free'" size="small" @click="openCheckInDialog(row)">入住</el-button>
          <el-button v-else size="small" type="success" @click="checkOutBed(row.id)">退住</el-button>
          <el-button size="small" @click="openDetailDialog(row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog title="床位管理" v-model="dialogVisible">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="楼号" prop="buildingNo">
          <el-input v-model="form.buildingNo" />
        </el-form-item>
        <el-form-item label="床位号" prop="bedNo">
          <el-input v-model="form.bedNo" />
        </el-form-item>
        <el-form-item label="房间号" prop="roomNo">
          <el-input v-model="form.roomNo" />
        </el-form-item>
        <el-form-item label="状态" prop="bedStatus">
          <el-select v-model="form.bedStatus">
            <el-option label="占用" value="occupied" />
            <el-option label="空闲" value="free" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBed">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog title="入住管理" v-model="checkInDialogVisible">
      <el-form :model="checkInForm" :rules="checkInRules" ref="checkInFormRef">
        <el-form-item label="选择客户" prop="customerId">
          <el-select v-model="checkInForm.customerId" placeholder="请选择客户">
            <el-option v-for="customer in customers" :key="customer.id" :label="customer.customerName" :value="customer.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="入住日期" prop="startDate">
          <el-date-picker v-model="checkInForm.startDate" type="date" placeholder="请选择入住日期" />
        </el-form-item>
        <el-form-item label="退住日期" prop="endDate">
          <el-date-picker v-model="checkInForm.endDate" type="date" placeholder="请选择退住日期" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="checkInDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCheckIn">确认入住</el-button>
      </template>
    </el-dialog>

    <el-dialog title="床位详情" v-model="detailDialogVisible">
      <div style="height: 300px; overflow: auto;">
        <el-table :data="detailCustomers" style="width: 100%">
          <el-table-column v-for="(col, index) in tableColumns" :key="index" :prop="col.prop" :label="col.label" />
        </el-table>
      </div>
      <el-empty v-if="detailCustomers.length === 0" description="暂无数据" />
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 显示查询结果提示 -->
    <p v-if="queryResultMessage" :style="{ color: queryResultColor }">{{ queryResultMessage }}</p>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import http from '@/axios/http';

const currentBed = ref(null);
const checkInFormRef = ref(null);
const detailDialogVisible = ref(false);
const detailCustomers = ref([]);
const checkInDialogVisible = ref(false);
const checkInForm = ref({ customerId: null, startDate: null, endDate: null });
const checkInRules = ref({
  customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择入住日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择退住日期', trigger: 'change' }]
});
const customers = ref([]);
const formRef = ref(null);
const searchId = ref('');
const queryResultMessage = ref('');
const queryResultColor = ref('');
const beds = ref([]);
const dialogVisible = ref(false);

// 定义表格列配置
const tableColumns = ref([
  { prop: 'id', label: 'ID' },
  { prop: 'bedId', label: '床位 ID' },
  { prop: 'buildingNo', label: '楼号' },
  { prop: 'bedNo', label: '床位号' },
  { prop: 'roomNo', label: '房间号' },
  { prop: 'customerName', label: '客户姓名' },
  { prop: 'customerAge', label: '年龄' },
  { prop: 'customerSex', label: '性别' },
  { prop: 'idcard', label: '身份证号' },
  { prop: 'startDate', label: '入住日期' },
  { prop: 'endDate', label: '退住日期' }
]);

const openDetailDialog = (row) => {
  http.get(`/lyy/beds/details/${row.id}`).then(response => {
    console.log('响应数据：', response.data);
    // 处理日期格式
    response.data.forEach(item => {
      if (item.startDate) {
        item.startDate = formatDate(item.startDate);
      }
      if (item.endDate) {
        item.endDate = formatDate(item.endDate);
      }
    });
    detailCustomers.value = response.data;
    detailDialogVisible.value = true;
  }).catch(error => {
    console.error('获取详情失败', error);
  });
};

const fetchCustomers = async () => {
  try {
    const response = await http.get('/lyy/getCustomers');
    customers.value = response.data;
  } catch (error) {
    console.error('获取客户失败', error);
  }
};

onMounted(() => {
  fetchBeds();
  fetchCustomers();
});

const handleCheckIn = async () => {
  try {
    if (checkInFormRef.value) {
      await checkInFormRef.value.validate();
      const { customerId, startDate, endDate } = checkInForm.value;
      if (currentBed.value) {
        await http.post(`/lyy/beds/checkIn/${currentBed.value.id}`, { customerId, startDate, endDate });
        await fetchBeds();
        checkInDialogVisible.value = false;
      }
    }
  } catch (error) {
    console.error('入住失败', error);
  }
};

const checkOutBed = async (id) => {
  try {
    await http.post(`/lyy/beds/checkOut/${id}`);
    await fetchBeds();
  } catch (error) {
    console.error('退住失败', error);
  }
};

const openCheckInDialog = (row) => {
  checkInDialogVisible.value = true;
  currentBed.value = row;
  checkInForm.value = { customerId: null, startDate: null, endDate: null };
};

const form = ref({
  id: null,
  bedNo: '',
  roomNo: '',
  bedStatus: '',
  buildingNo: ''
});

const rules = ref({
  buildingNo: [{ required: true, message: '请输入楼号', trigger: 'change' }],
  bedNo: [{ required: true, message: '请输入床位号', trigger: 'blur' }],
  roomNo: [{ required: true, message: '请输入房间号', trigger: 'blur' }],
  bedStatus: [{ required: true, message: '请选择状态', trigger: 'change' }]
});

const fetchBeds = async () => {
  try {
    const response = await http.get('/lyy/beds');
    beds.value = response.data;
  } catch (error) {
    console.error('获取床位数据失败', error);
  }
};

const openCreateDialog = () => {
  dialogVisible.value = true;
  form.value = { id: null, bedNo: '', roomNo: '', bedStatus: '', buildingNo: '' };
};

const saveBed = async () => {
  try {
    if (formRef.value) {
      await formRef.value.validate();
      if (form.value.id) {
        await http.put(`/lyy/beds`, form.value);
      } else {
        await http.post(`/lyy/beds`, form.value);
      }
      await fetchBeds();
      dialogVisible.value = false;
    }
  } catch (error) {
    console.error('保存失败', error);
  }
};

const queryBedById = async () => {
  if (!searchId.value) {
    queryResultMessage.value = '请输入有效的床位 ID';
    queryResultColor.value = 'red';
    return;
  }
  try {
    const response = await http.get(`/lyy/beds/${searchId.value}`);
    if (response.data) {
      beds.value = [response.data];
      queryResultMessage.value = '查询成功';
      queryResultColor.value = 'green';
    } else {
      await fetchBeds();
      queryResultMessage.value = '未找到该床位信息';
      queryResultColor.value = 'red';
    }
  } catch (error) {
    await fetchBeds();
    queryResultMessage.value = '查询失败，请检查网络或输入的 ID';
    queryResultColor.value = 'red';
    console.error('查询失败', error);
  }
};

onMounted(fetchBeds);

// 自定义日期格式化函数
function formatDate(dateStr) {
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
</script>

<style scoped>
.container {
  padding: 20px;
}
.el-table {
  margin-top: 15px;
}
.el-dialog {
  width: 400px;
}
.el-dialog__body {
  padding: 20px;
}
</style>